package com.android.multiplesmart.utils;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

public class WebSocketChecker {

    private static final OkHttpClient client = new OkHttpClient();

    public interface WebSocketCheckCallback {
        void onSuccess();
        void onFailure(Throwable t);
    }

    public static void checkWebSocket(String url, final WebSocketCheckCallback callback) {
        Request request = new Request.Builder()
                .url(url)
                .build();

        // 创建WebSocket对象，并设置监听器
        WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, okhttp3.Response response) {
                // 连接成功，关闭WebSocket
                webSocket.close(1000, "Check Successful");
                if (callback != null) {
                    callback.onSuccess();
                }
            }


            @Override
            public void onFailure(WebSocket webSocket, Throwable t, @javax.annotation.Nullable okhttp3.Response response) {
                // 连接失败
                if (callback != null) {
                    callback.onFailure(t);
                }
            }
        });
    }
}